package jdbc.homework;

import java.sql.*;
import java.util.Scanner;

public class RegisterDemo {
    public static void main(String[] args) {
        //用户输入信息
        Scanner sc = new Scanner(System.in);
        System.out.println("欢迎使用注册功能！！！");
        System.out.println("请输入用户名：");
        String userName = sc.nextLine();
        System.out.println("请输入密码：");
        String password = sc.nextLine();
        System.out.println("请输入昵称：");
        String nickName = sc.nextLine();
        System.out.println("请输入年龄：");
        int age = sc.nextInt();

        try (Connection connection = DButil.getConnection()) {
            //判断用户名是否存在
            Statement statement = connection.createStatement();
            String sqlUName = "SELECT username FROM user WHERE username = '" + userName + "'";
            ResultSet rs = statement.executeQuery(sqlUName);
            if (rs.next()) {
                System.out.println("用户名已存在，请更换用户名！！！");
                System.out.println("请输入用户名：");
            } else {
                //用户名不存在，进行信息录入
                String sql = "INSERT INTO user(username, password, nickname, age) VALUES (?,?,?,?)" ;
                PreparedStatement ps = connection.prepareStatement(sql);
                ps.setString(1,userName);
                ps.setString(2,password);
                ps.setString(3,nickName);
                ps.setInt(4,age);
                int num = ps.executeUpdate();
                System.out.println(num > 0 ? "注册成功！！！" : "注册失败！！！");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        sc.close();
    }
}
